package com.zzyl.intercept;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description CustormerInterceptor
 * @Author luohai
 * @Date 2024-10-20
 */
@Component
@Slf4j
public class CustomerInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断是否是处理器资源，如果不是就放行
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        //获取请求头里的token
        String token = request.getHeader(Constants.USER_TOKEN);
        //判断token是否为空
        if (token == null){
            throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
        }
        //解析token，拿到载荷
        Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
        //获取载荷里的用户id
        Long id = MapUtil.get(claims, Constants.JWT_USERID, Long.class);
        //将用户id打印到日志
        log.info("CustomerInterceptor中的preHandle方法的用户id为{}",id);

        UserThreadLocal.set(id);
        //拦截器放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}

